import {
	Button,
	IconButton,
	ImageList,
	ImageListItem,
	Stack,
	Typography,
	styled,
} from '@mui/material'
import { useEffect, useState } from 'react'
import Image, {
	ImageType,
	StyledDislikeIcon,
	StyledLikeIcon,
} from '../cardlist/image'
import { selectCartProducts, selectUser } from '../../store/reducers/selectors'
import { useAppDispatch, useAppSelector } from '../../hooks'
import Reviews from './reviews'
import {
	useGetProductQuery,
	useSetDislikeMutation,
	useSetLikeMutation,
} from '../../api/productsApiSlice'
import { useParams } from 'react-router-dom'
import { cartSlice } from '../../store/reducers/slices/cartSlice'
import AmountSelector from '../cart/amountSelector'
import DeleteFromCartButton from '../cart/deleteFromCartButton'

const StyledPrice = styled(Typography)(() => ({
	fontFamily: 'Nunito',
	fontSize: '14px',
	fontWeight: '400',
	lineHeight: '20px',
	letterSpacing: '0em',
	textAlign: 'left',
	textDecoration: 'line-through',
	color: '#1A1A1A',
}))

const StyledPriceWithDiscount = styled(Typography)(() => ({
	styleName: 'Header : H1/ExtraBold',
	fontFamily: 'Nunito',
	fontSize: '28px',
	fontWeight: '800',
	lineHeight: '32px',
	letterSpacing: '0em',
	textAlign: 'left',
	color: '#F44336',
}))

const StyledFavorite = styled(Typography)(() => ({
	styleName: 'Body : S1/Regular',
	fontFamily: 'Nunito',
	fontSize: '12px',
	fontWeight: '400',
	lineHeight: '14px',
	letterSpacing: '0em',
	textAlign: 'left',
	color: '#7B8E98',
}))

const StyledButton = styled(Button)(() => ({
	width: '121px',
	height: '40px',
	borderRadius: '55px',
	background: '#FFE44D',
	border: '0px',
	'&': {
		color: '#1A1A1A',
		textTransform: 'none',
	},
}))

const Body = () => {
	const dispatch = useAppDispatch()
	const cartProducts = useAppSelector(selectCartProducts)

	const { productId } = useParams()
	const { data: productData } = useGetProductQuery({ id: productId || '' })

	const user = useAppSelector(selectUser)

	const [like, setLike] = useState(false)

	const [setLikeRequestFn] = useSetLikeMutation()
	const [setDislikeRequestFn] = useSetDislikeMutation()

	function handleClick() {
		if (productData?._id) {
			if (like) {
				setDislikeRequestFn({ _id: productData._id })
			} else {
				setLikeRequestFn({ _id: productData._id })
			}
		}
	}

	useEffect(() => {
		setLike(productData?.likes.includes(user?._id || '') || false)
	}, [user?._id, productData?.likes])

	const addedToCart = cartProducts?.find(
		(product) => product._id === productData?._id
	)

	function handleAddToCartClick() {
		if (!productData) return
		dispatch(
			cartSlice.actions.addProduct({
				_id: productData._id,
				name: productData.name,
				pictures: productData.pictures,
				stock: productData.stock,
				price: productData.price,
				purchaseAmount: 1,
				discount: productData.discount,
			})
		)
	}

	return (
		<>
			<Stack direction={'row'} justifyContent={'space-between'}>
				<Stack>
					<Image
						_id={productData?._id || ''}
						type={ImageType.productCard}
						discount={productData?.discount || 0}
						pictures={productData?.pictures || ''}
					/>
				</Stack>
				<Stack>
					<ImageList
						sx={{
							display: 'flex',
							width: 80,
							height: 488,
							flexDirection: 'column',
						}}
						cols={1}
						rowHeight={80}
						gap={0}
					>
						<ImageListItem key={productData?._id}>
							<img
								srcSet={`${productData?.pictures}`}
								src={`${productData?.pictures}`}
								alt={productData?.name}
								loading='lazy'
							/>
						</ImageListItem>
					</ImageList>
				</Stack>
				<Stack
					sx={{
						display: 'flex',
						width: 343,
						height: 488,
						flexDirection: 'column',
					}}
				>
					{productData?.discount !== 0 ? (
						<>
							<StyledPrice>{productData?.price} ₽</StyledPrice>
							<StyledPriceWithDiscount>
								{productData?.price && productData.discount
									? productData?.price * ((100 - productData.discount) / 100)
									: 0}{' '}
								₽
							</StyledPriceWithDiscount>
						</>
					) : (
						<Typography>{productData?.price} ₽</Typography>
					)}
					<Stack direction={'row'} alignItems={'center'} spacing={1}>
						<IconButton
							data-testid={`TO_FAVORITES_BUTTON_${productData?._id}`}
							sx={{ gap: '10px' }}
							onClick={handleClick}
						>
							{like ? <StyledLikeIcon /> : <StyledDislikeIcon />}
							<StyledFavorite>
								{like ? 'Удалить из избранного' : 'В избранное'}
							</StyledFavorite>
						</IconButton>
					</Stack>

					{addedToCart && productData ? (
						<Stack direction={'row'} spacing={2}>
							<AmountSelector _id={productData._id} />
							<DeleteFromCartButton _id={productData._id} />
						</Stack>
					) : (
						<StyledButton variant='outlined' onClick={handleAddToCartClick}>
							<Typography>
								{productData && productData.stock > 1
									? 'В корзину'
									: 'Закончился'}
							</Typography>
						</StyledButton>
					)}
				</Stack>
			</Stack>
			<Reviews />
		</>
	)
}

export default Body
